<template>
  <div><el-tree
         ref="tree"
         default-expand-all
         :data="list"
         :props="{ label: 'name' }"
         show-checkbox
         check-strictly
         node-key="id"
       />
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small">取消</el-button>
        <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      </el-col>
    </el-row>
  </div>

</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()

    this.loadPermissionById()
  },
  methods: {
    // 点击了 分配的确定按钮
    async hSubmit() {
      // 接收
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log('当前选中的节点数组是', permIds)
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      console.log('保存角色的权限点的结果是', res)
      // 提示
      this.$message.success('保存角色的权限成功')

      // 子向父传值
      this.$emit('success')
    },

    async loadPermissionList() {
      const { data } = await getPermissionList()
      this.$refs.tree.getCheckedKeys(data.roleId)
      this.list = tranListToTreeData(data)
    },

    async loadPermissionById() {
      const res = await getRoleDetail(this.roleId)
      console.log('getRoleDetail', res)
      // 回填
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      // this.$refs.tree.setCheckedKeys([])
    }
  }
}
</script>
